package com.qlm.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.qlm.annoation.WeixinAuoth;
import com.qlm.cache.CacheManmager;
import com.qlm.cache.ShopCache;
import com.qlm.entity.Order;
import com.qlm.entity.ResultMsg;
import com.qlm.entity.User;
import com.qlm.interceptor.WeixinController;
import com.qlm.service.ShopMgr;
import com.qlm.tool.Delivery;
import com.qlm.tool.EmojiFilter;
import com.qlm.tool.WxUtil;

/**
 * 微信端的controller，仅此一个 需要继承@WeixinController
 * 
 * @author wangzih
 *
 */
public class MainController extends WeixinController {

	private String orderCommit = "commitorder";//是否重复提交订单
	
	ShopCache shopCache = CacheManmager.getObj("shop");
	
	private static String order_info_key = "order_info";
	
	@WeixinAuoth
	public void skip(){
		String url1 = getPara("url");
		String appId = PropKit.get("appid");
		String strBackUrl = PropKit.get("authoUrl") + "/toskip?url="+url1;
		String url = SnsAccessTokenApi.getAuthorizeURL(appId, strBackUrl, true);
		redirect(url);
	}
	public void toskip(){
		String p = getPara("url");
		redirect(p+"?openid="+getOpenId());
	}
	
	@WeixinAuoth
	public void index() {
		String p = getRequest().getQueryString();
		String strBackUrl = "";
		String appId = PropKit.get("appid");
		if(p != null && p.indexOf("id") != -1 && p.indexOf("scale") != -1){
			String id = getPara("id");
			String scale= getPara("scale");
			strBackUrl = PropKit.get("authoUrl") + "/register?data="+id+"*"+scale;
			String url = SnsAccessTokenApi.getAuthorizeURL(appId, strBackUrl, false);
			redirect(url);
			return ;
		}
		if(p== null){
			p = "l";
			strBackUrl = PropKit.get("authoUrl") + "/shop?openid="+p;
		}else{
			strBackUrl = PropKit.get("authoUrl") + "/shop?openid="+p;
		}
		String url = SnsAccessTokenApi.getAuthorizeURL(appId, strBackUrl, false);
		redirect(url);
	}
	
	public void register(){
		String data = getPara("data");
		if(data == null){
			renderText("该码已经失效");
			return;
		}
		String[] datas = data.split("\\*");
		String id = datas[0];
		String scale = datas[1];
		String openid = getOpenId();
		String userName = getNickName();
		String filterEmoji = EmojiFilter.filterEmoji(userName);
		try{
			Db.update("insert into t_scale (id,openid,nick_name,scale) values("+id+",'"+openid+"','"+filterEmoji+"','"+scale+"')");
		}catch(Exception e){
			renderText("该码已经失效");
			return;
		}
		shopCache.updateScale();
		renderText("您已经成功添加到经销商");
	}
	
	public void shop(){
		String shareid = getPara("openid");
		if(!"l".equals(shareid)){
			ShopMgr.addShare(getOpenId(), shareid);
		}
		List<Record> imgs = shopCache.getImgs();
		List<Record> gifts = shopCache.getGifts(getOpenId());
		setAttr("imgs", imgs);
		setAttr("gifts", gifts);
		render("/shop/index.jsp");
	}
	
	public void detail(){
		String id = getPara("id");
		Record gift = shopCache.getGift(id,getOpenId());
		setAttr("gift", gift);
		List<Record> comments = ShopMgr.getComments(id);
		setAttr("comments", comments);
		render("/shop/detail.jsp");
	}
	
	public void shopcar(){
		List<Record> shopCar = ShopMgr.getShopCar(getOpenId());
		List<Record> gifts = new ArrayList<Record>();
		for (Record record : shopCar) {
			Integer gift_id = WxUtil.getInt("gift_id_", record);
			Record gift = shopCache.getGift(gift_id+"",getOpenId());
			Integer count_ = WxUtil.getInt("count_", record);
			gift.set("count_", count_);
			Integer shopcarid = WxUtil.getInt("id", record);
			gift.set("shopcarid", shopcarid);
			gifts.add(gift);
		}
		removeSessionAttr(orderCommit);
		setAttr("gifts", gifts);
		render("/shop/shopcart.jsp");
	}
	
	/**
	 * 删除购物车商品
	 */
	public void delShopCar(){
		String id = getPara("id");
		ShopMgr.delShopCar(id);
		JSONObject obj = new JSONObject();
		obj.put("status", true);
		renderJson(obj.toString());
	}

	/**
	 *  更新购物车商品数量
	 */
	public void updateNum(){
		String id = getPara("id");
		String count = getPara("count","1");
		ShopMgr.updateShopCarNum(id, count);
		JSONObject obj = new JSONObject();
		obj.put("status", true);
		renderJson(obj.toString());
	}
	
	public void checkorder(){
		Object sessionAttr = getSessionAttr(orderCommit);
		ResultMsg msg = new ResultMsg();
		if(sessionAttr != null){//说明返回按钮，这个时候页面要跳到购物车
			msg.setStatus(true);
		}else{
			
		}
		renderJson(msg);
	}
	
	public void makeOrder(){
		Integer id = getParaToInt("addressid", -1);// 先判断是不是传收货地址
		String totalStr = getPara("total","0");
		double total = 0;
		List<Record> info = null;
		List<Record> yhq = null;
		if (id == -1) {
			total = Double.parseDouble(totalStr);
			id = WxUtil.getInt("def_add", getUser());
			String para = getPara("data");
			Record res = new Record();
			JSONArray parseArray = JSON.parseArray(para);
			int size = parseArray.size();
			info = new ArrayList<Record>();
			yhq = ShopMgr.getYhq(total,getOpenId());
			res.set("list", info);
			res.set("total", total);
			res.set("yhq", yhq);
			for (int i = 0; i < size; i++) {
				JSONObject obj = parseArray.getJSONObject(i);
				String giftid = obj.getString("id");
				Record gift = shopCache.getGift(giftid,getOpenId());
				Record r = new Record();
				info.add(r);
				String count = obj.getString("count");
				String shopcarid = obj.getString("shopcarid");
				Object object = gift.get("price_");
				r.set("id", giftid).set("count_", count).set("shopcarid_", shopcarid)
				.set("price_", object).set("img_", gift.get("img_"));
			}
			setSessionAttr(order_info_key, res);
		} else {// 收货地址入口进来的，从session取值
			Record res = getSessionAttr(order_info_key);
			if(res != null){
				info = res.get("list");
				yhq = res.get("yhq");
			}else{
				redirect("/shop");
				return;
			}
			total = res.getDouble("total");
		}
		Record defaultAddress = ShopMgr.getAddress(id);
		setAttr("address", defaultAddress);
		setAttr("info", info);
		setAttr("yhqjson",yhqJson(yhq));
		setAttr("yhqs", yhq);
		render("/shop/order.jsp");
	}
	
	private String yhqJson(List<Record> yhq){
		Record all = new Record();
		for (Record record : yhq) {
			Record r = new Record();
			Object type = record.get("type_");
			r.set("type", type);
			r.set("yhmoney", record.get("yhmoney_"));
			r.set("discount", record.get("discount_"));
			Integer id = WxUtil.getInt("id", record);
			all.set(""+id, r);
		}
		return JsonKit.toJson(all);
	}
	
	public void yhq(){
		setAttr("json", JsonKit.toJson(ShopMgr.getYHQ(getOpenId())));
		render("/shop/yhq.jsp");
	}
	/**
	 * 收货地址页面
	 */
	public void address(){
		User user = getUser();
		Record[] address = ShopMgr.getAddress(user);
		String type = getPara("type","person");
		Integer defId = WxUtil.getInt("def_add", user);
		int selectId = defId;
		if("order".equals(type)){
		    selectId = getParaToInt("addressid",defId);
		}else if("modify".equals(type)){
			String orderId = getPara("orderid");
			setAttr("orderid", orderId);
			Order findById = Order.dao.findById(orderId);
			Integer addr_id_ = WxUtil.getInt("addr_id_", findById,defId);
			selectId = addr_id_;
		}
		setAttr("selectid", selectId);
		setAttr("type", type);
		setAttr("list", address);
		
		setAttr("defId", defId);
		render("/shop/gladdress.jsp");
	}
	
	public void deleteAddress(){
		String id = getPara("id");
		Integer default_id = WxUtil.getInt("def_add", getUser());
		ResultMsg msg = new ResultMsg();
		if((default_id+"").equals(id)){
			msg.setStatus(false);
			msg.setMsg("无法删除默认收货地址");
		}else{
			ShopMgr.deleteAddress(id, getOpenId());
			msg.setStatus(true);
		}
		renderJson(msg);
	}
	
	public void editAddress(){
		Integer id = getParaToInt("id",-1);
		String type = getPara("type","person");
		if("modify".equals(type)){
			setAttr("orderid", getPara("orderid"));
		}
		Integer defId = WxUtil.getInt("def_add", getUser());
		int selectId = defId;
		setAttr("type", type);
		if(id == -1){
			
		}else{
			Record address = ShopMgr.getAddress(id);
			selectId = id; 
			if(defId == id){
				setAttr("def", true);
			}
			setAttr("address", address);
		}
		setAttr("selectid", selectId);
		render("/shop/address.jsp");
	}
	
	public void saveAddress(){
		String id = getPara("id","");
		String tel = getPara("tel");
		String name = getPara("name");
		String addr = getPara("address");
		Boolean paraToBoolean = getParaToBoolean("def",false);
		ResultMsg msg = ShopMgr.saveAddress(id, getUser(),name,tel,addr,paraToBoolean);
		renderJson(msg);
	}
	
	
	public void modifyAddress(){
		String orderid = getPara("orderid");
		int addrId = getParaToInt("addrid");
		ResultMsg msg = ShopMgr.modifyAddrees(orderid,addrId);
		renderJson(msg);
	}
	/**
	 * 设置默认地址
	 */
	public void setAddressDef(){
		String id = getPara("id");
		getUser().set("def_add", id).update();
		renderJson(new Record());
	}
	
	/**
	 * 下单页面
	 */
	public void addOrder(){
		Object sessionAttr = getSessionAttr(orderCommit);
		if(sessionAttr != null){
			renderText("订单重复提交，请返回");
			return;
		}
		String address = getPara("address");
		String vals = getPara("vals");
		String yhqval = getPara("yhqval","-1");
		String beizhu = getPara("beizhu","");
		ResultMsg addOrder = ShopMgr.addOrder(getUser(),vals,address,beizhu,yhqval);
		Order o = addOrder.getObj();
		setSessionAttr(orderCommit, o);
		String id = o.getStr("id");
		redirect("/pay?id="+id);
	}
	
	/**
	 *  订单中心
	 */
	public void orderPage(){
		render("/shop/allorder.jsp");
	}
	
	public void getOrder(){
		List<Record> orderByUser = ShopMgr.getOrderByUser(getOpenId());
		renderJson(orderByUser);
	}
	
	public void orderdetail(){
		String id = getPara(0);
		Record order = ShopMgr.getOrder(id,getOpenId());
		setAttr("order", order);
		render("/shop/orderdetail.jsp");
	}
	
	public void queryDelivery(){
		String id = getPara("num");
		Delivery query = Delivery.query(id);
		ResultMsg msg = new ResultMsg();
		if(query.isSuccess()){
			StringBuilder sb = new StringBuilder();
			Delivery[] data = query.getData();
			int len = data.length;
			for (int i= 0; i <len; i++) {
				sb.append(data[i].getTime()+","+data[i].getContext()+"<br>");
			}
			msg.setMsg(sb.toString());
		}else{
			msg.setMsg("暂时没有查到物流信息.");
		}
		renderJson(msg);
	}
	
	public void addComment(){
		String id = getPara("id");
		String text = getPara("text");
		String oid = getPara("oid");
		String orderid = getPara("orderid");
		ResultMsg addComment = ShopMgr.addComment(id, text, getUser(),oid,orderid);
		renderJson(addComment);
	}
	
	public void cancelOrder(){
		String id = getPara(0);
		ResultMsg addComment = ShopMgr.cancerOrder(id);
		renderJson(addComment);
	}
	/**
	 * 收货
	 */
	public void receive(){
		String id = getPara(0);
		ResultMsg receive = ShopMgr.receive(id, getOpenId());
		renderJson(receive);
	}
	
	public void person(){
		User user = getUser();
		setAttr("user", user);
		render("/shop/member.jsp");
	}
	
	/**
	 * 个人信息
	 */
	public void info(){
		render("/shop/member.jsp");
	}
	
	public void saveInfo(){
		String tel = getPara("tel");
		String address =getPara("address");
		String name = getPara("name");
		String date = getPara("date");
		address = EmojiFilter.filterEmoji(address);
		name = EmojiFilter.filterEmoji(name);
		getUser().set("tel", tel).set("real_name", name).set("birth", date).set("addr", address).update();
		renderJson(new Record());
	}
	
	/**
	 * 添加到购物车
	 */
	public void addShopCar(){
		String id = getPara("id");
		String count = getPara("count");
		ResultMsg msg = ShopMgr.addShopCar(getOpenId(), id, count);
		renderJson(msg);
	}
	
	public void sendYhq(){
		Integer shareget = WxUtil.getInt("shareget", getUser());
		if(shareget != 1){
			ShopMgr.sendYhq(getOpenId(), 1);
			getUser().set("shareget", 1).update();
		}
		renderText("ok");
	}
}
